﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Toenda.Foundation.Parser {
	/// <summary>
	/// Provides a parser to parse simple text formated with BBCode to the Html format.
	/// </summary>
	public class BBCode {
		/*
* Auszeichnungselement [elementname] [/elementname] <elementname> </elementname>
einfache Schriftformatierung [b]fett[/b]
[i]kursiv[/i]
[u]unterstrichen[/u]
[center]zentriert[/center] <b>fett</b>
<i>kursiv</i>
<u>unterstrichen</u>
<center>zentriert</center>
erweiterte Schriftformatierung [font="schriftart"]text[/font]
[color="farbe"]text[/color]
[size="schriftgröße"]text[/size] <font face="schriftart">text</font>
<font color="farbe">text</font>
<font size="schriftgröße">text</font>
Gliederung ... lorem ipsum
Leerzeile
dolor ... <p>... lorem ipsum</p>
<p>dolor ...</p>
Aufzählungslisten [list]
 [*]Punkt
 [*]Punkt
[/list] <ul>
 <li>Punkt</li>
 <li>Punkt</li>
</ul>
Verweise [url=example.com]linktext[/url]
[url]example.com[/url] <a href="http://example.com">linktext</a>
<a href="http://example.com">example.com</a>
Bilder [img]example.com/bild.jpg[/img] <img src="http://example.com/bild.png" alt="bild.png" />
Smileys :) <img src="/smileys/happy.png" alt="Smilie" />
* */

		private string _buffer;

		/// <summary>
		/// Initializes a new instance of the <see cref="BBCode"/> class.
		/// </summary>
		public BBCode() {
			this._buffer = string.Empty;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="BBCode"/> class.
		/// </summary>
		/// <param name="buffer">The buffer.</param>
		public BBCode(string buffer) {
			this._buffer = buffer;
		}

		public string Parse() {
			this._buffer = ConvertUrl(this._buffer, "cnt", "", "\">");

			return this._buffer;
		}

		public string Parse(string buffer) {
			this._buffer = buffer;

			return this.Parse();
		}

		public static string ConvertUrl(string buffer) {
			return ConvertUrl(buffer, "cnt", "", "");
		}

		public static string ConvertUrl(string buffer, string matchTag, string linkPrefix, string linkPostfix) {
			buffer = buffer.Replace("[URL=", "<a href=\"" + linkPrefix);

			Regex pattern = new Regex(@"(\])(?<" + matchTag + @">[A-Za-z0-9]*)(\[)");

			buffer = pattern.Replace(buffer, linkPostfix + "${" + matchTag + "}");
			buffer = buffer.Replace("/URL]", "</a>");

			return buffer;
		}
	}
}
